<?php

namespace App\Models\Entity\sys_categories;

use Encore\Admin\Traits\AdminBuilder;
use Encore\Admin\Traits\ModelTree;
use Eloquent as Model;
use Illuminate\Support\Facades\Redis;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * Class sys_categories
 * @package App\Models\Entity\sys_categories
 * @version June 21, 2018, 3:47 pm CST
 *
 * @property string title
 * @property integer parent_id
 * @property string description
 * @property integer listorder
 */
class sys_categories extends Model
{
    use SoftDeletes, ModelTree, AdminBuilder;


    public $table = 'sys_categories';
    

    protected $dates = ['deleted_at'];


    public $fillable = [
        'title',
        'parent_id',
        'description',
        'listorder'
    ];

    /**
     * The attributes that should be casted to native types.
     *
     * @var array
     */
    protected $casts = [
        'title' => 'string',
        'parent_id' => 'integer',
        'description' => 'string',
        'listorder' => 'integer'
    ];

    /**
     * Validation rules
     *
     * @var array
     */
    public static $rules = [
        'title' => 'required||max:100',
        'parent_id' => 'required|integer',
        'listorder' => 'required|integer'
    ];

    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);

        $this->setParentColumn('parent_id');
        $this->setOrderColumn('listorder');
        $this->setTitleColumn('title');
    }

    public function tags()
    {
        return $this->hasMany('\App\Models\Entity\Tag\tag','tag_group', 'id');
    }


    public function tagGroup($getcache=true){
        //Redis::set('sys:tag_groups','');
        if($getcache){
            $tag_groups = Redis::get('sys:tag_groups');
            //print_r($tag_groups);
            if(!empty($tag_groups)){
                return $tag_groups;
            }
        }
        $tag_groups =  $this->select('id','title','parent_id','listorder')->get();
        foreach ($tag_groups as &$tag_group){
            $tag_group['tags'] = $this->find($tag_group['id'])->tags;
        }
        Redis::set('sys:tag_groups',$tag_groups);
        return $tag_groups->toJson();
    }
}
